﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace Hybrid.Threading.Sync
{
    class Transaction
    {
        private DateTime m_timeOfLastTrans;
        public void PerformTransaction()
        {
            Monitor.Enter(this);
            // 以下代码拥有对数据的独占访问权
            m_timeOfLastTrans = DateTime.Now;
            Monitor.Exit(this);
        }
        public DateTime LastTransaction
        {
            get
            {
                Monitor.Enter(this);
                // 以下代码拥有对数据的共享访问权
                DateTime temp = m_timeOfLastTrans;
                Monitor.Exit(this);
                return temp;
            }
        }


    }


    class Transaction2
    {

        private DateTime m_timeOfLastTrans;
        //现在每个对象都有一个私有的锁
        private readonly object m_lock = new object();
        public void PerformTransaction()
        {
            Monitor.Enter(m_lock);
            // 以下代码拥有对数据的独占访问权
            m_timeOfLastTrans = DateTime.Now;
            Monitor.Exit(m_lock);
        }
        public DateTime LastTransaction
        {
            get
            {
                Monitor.Enter(m_lock);
                // 以下代码拥有对数据的共享访问权
                DateTime temp = m_timeOfLastTrans;
                Monitor.Exit(m_lock);
                return temp;
            }
        }
    }


    class Transaction3 : IDisposable
    {
        private readonly ReaderWriterLockSlim m_lock = new ReaderWriterLockSlim(LockRecursionPolicy.NoRecursion);
        private DateTime m_timeOfLastTrans;
        public void PerformTransaction()
        {
            m_lock.EnterWriteLock();
            // 以下代码拥有对数据的独占访问权
            m_timeOfLastTrans = DateTime.Now;
            m_lock.ExitWriteLock();
        }
        public DateTime LastTransaction
        {
            get
            {
                m_lock.EnterReadLock();
                // 以下代码拥有对数据的共享访问权
                DateTime temp = m_timeOfLastTrans;
                m_lock.ExitReadLock();
                return temp;
            }
        }
        public void Dispose() { m_lock.Dispose(); }
    }
}
